package com.zuo_book.common;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zuo_book.entity.User;
import com.zuo_book.mapper.UserMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * 安全工具类
 */
@Component
public class SecurityUtils {

    private static UserMapper userMapper;

    public SecurityUtils(UserMapper userMapper) {
        SecurityUtils.userMapper = userMapper;
    }

    /**
     * 获取当前登录用户ID
     * @return 用户ID
     */
    public static Long getCurrentUserId() {
        String username = getCurrentUsername();
        if (username == null) {
            return null;
        }

        // 如果是开发环境，返回默认用户ID
        if (System.getProperty("spring.profiles.active", "").contains("dev")) {
            return 1L;
        }

        // 从数据库查询用户ID
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username));
        return user != null ? user.getId() : null;
    }

    /**
     * 获取当前登录用户名
     * @return 用户名
     */
    public static String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated() ||
            authentication.getPrincipal().equals("anonymousUser")) {
            return null;
        }

        if (authentication.getPrincipal() instanceof UserDetails) {
            return ((UserDetails) authentication.getPrincipal()).getUsername();
        }
        return authentication.getName();
    }

    /**
     * 判断当前用户是否已认证
     * @return 是否已认证
     */
    public static boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && authentication.isAuthenticated() &&
               !authentication.getPrincipal().equals("anonymousUser");
    }

    /**
     * 获取当前用户角色
     * @return 用户角色
     */
    public static String getCurrentUserRole() {
        String username = getCurrentUsername();
        if (username == null) {
            return null;
        }
//
//        // 如果是开发环境，返回默认角色
//        if (System.getProperty("spring.profiles.active", "").contains("dev")) {
//            return "ADMIN";
//        }

        // 从数据库查询用户角色
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username));
        return user != null ? user.getRole() : null;
    }
}
